package jmine.tec.rpc.common.serialization.json;

import java.util.ArrayList;
import java.util.List;

import jmine.tec.json.JSON;
import jmine.tec.json.JSONArray;

/**
 * Conversor de JSON para Java e vice-versa
 * 
 * @author lundberg
 */
public class JSONListConverter implements JSONConverterStrategy {

    /**
     * {@inheritDoc}
     */
    public boolean matchesJava(Object object) {
        return object instanceof List;
    }

    /**
     * {@inheritDoc}
     */
    public boolean matchesJSON(JSON json) {
        return json instanceof JSONArray;
    }

    /**
     * {@inheritDoc}
     */
    public Object toJava(JSONConversionContext context, JSON json) {
        JSONArray jsonArray = (JSONArray) json;
        List<Object> list = new ArrayList<Object>(jsonArray.getSize());
        for (int i = 0; i < jsonArray.getSize(); i++) {
            list.add(context.toJava(jsonArray.getProperty(i)));
        }
        return list;
    }

    /**
     * {@inheritDoc}
     */
    public JSON toJSON(JSONConversionContext context, Object object) {
        List<?> list = (List<?>) object;
        List<JSON> elements = new ArrayList<JSON>(list.size());
        for (Object e : list) {
            elements.add(context.toJSON(e));
        }
        return new JSONArray(elements);
    }
}
